package com.danceforyou.receipt.service.impl;

import com.danceforyou.common.restful.exception.BizExceptionEnum;
import com.danceforyou.common.service.OperationService;
import com.danceforyou.common.service.impl.BaseServiceImpl;
import com.danceforyou.common.util.AssertUtil;
import com.danceforyou.common.util.Constants;
import com.danceforyou.medium.service.MediumService;
import com.danceforyou.order.model.OrderDO;
import com.danceforyou.order.service.OrderService;
import com.danceforyou.ossFile.model.OssFileDO;
import com.danceforyou.ossFile.service.OssFileService;
import com.danceforyou.receipt.dao.ReceiptDAO;
import com.danceforyou.receipt.model.ReceiptDO;
import com.danceforyou.receipt.model.ReceiptVoucherDO;
import com.danceforyou.receipt.service.ReceiptService;
import com.danceforyou.receipt.service.ReceiptVoucherService;
import com.danceforyou.receipt.vo.ReceiptVO;
import com.danceforyou.user.vo.UserVO;
import com.danceforyou.websocket.BacklogSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
* 类名称：ReceiptServiceImpl
* 创建人：danceforyou
* 创建时间：2021年02月07日
* 版本号：1.0v
*/
@Service("receiptService")
public class ReceiptServiceImpl extends BaseServiceImpl<Long, ReceiptDO, ReceiptVO, ReceiptDAO> implements ReceiptService {
    @Autowired
    private ReceiptDAO receiptDAO;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MediumService mediumService;
    @Autowired
    private OssFileService ossFileService;
    @Autowired
    private ReceiptVoucherService receiptVoucherService;
    @Autowired
    private OperationService operationService;
    @Autowired(required = false)
    private HttpSession session;

    @Override
    public ReceiptDAO getDao() {
        return receiptDAO;
    }

    @Override
    public void saveInfo(ReceiptDO receipt) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        //查询排期信息
        OrderDO order = orderService.getById(receipt.getOrderId());
        AssertUtil.notNull(order, "排期信息不存在，操作失败");
        AssertUtil.isTrue(!order.getIsReceipt(), "该排期已完成回款，请勿重复发起");
        //查询排期已回款金额（待审核、审核通过）
        BigDecimal recedMoney = this.sumByCondition("recMoney", new HashMap<String, Object>(){{
            put("orderId", receipt.getOrderId());
            put("statusList", new int[]{Constants.RECEIPT_STATUS_FILLIN, Constants.RECEIPT_STATUS_PASSED});
            put("isDelete", false);
        }});
        BigDecimal reRecMoney = order.getQuotedPrice().subtract(recedMoney);
        AssertUtil.isTrue(receipt.getRecMoney().compareTo(reRecMoney) <= 0, "总回款金额不能大于排期执行价");
        receipt.setCreateUserId(loginUser.getId());
        receipt.setCreateDate(new Date());
        receipt.setStatus(Constants.RECEIPT_STATUS_FILLIN);
        receipt.setIsDelete(false);
        this.insert(receipt);
        operationService.saveOperation(Constants.OPER_TABLE_RECEIPT, receipt.getId(), Constants.OPER_ADD, loginUser, null);
        //发送待办消息
        BacklogSocket.sendBacklogMessage(Constants.MENU_BACKLOG_RECEIPT_AUDIT);
    }

    @Override
    public void updateInfo(ReceiptDO receipt) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        ReceiptDO temp = this.getById(receipt.getId());
        AssertUtil.notNull(temp, "信息不存在");
        AssertUtil.isTrue(temp.getStatus() == Constants.RECEIPT_STATUS_FILLIN || temp.getStatus() == Constants.RECEIPT_STATUS_NOPASS, "该申请已审核通过，无法修改");
        //查询排期信息
        OrderDO order = orderService.getById(receipt.getOrderId());
        AssertUtil.notNull(order, "排期信息不存在，操作失败");
        //查询排期已回款金额（待审核、审核通过）
        BigDecimal recedMoney = this.sumByCondition("recMoney", new HashMap<String, Object>(){{
            put("orderId", receipt.getOrderId());
            put("statusList", new int[]{Constants.RECEIPT_STATUS_FILLIN, Constants.RECEIPT_STATUS_PASSED});
            put("isDelete", false);
        }});
        BigDecimal reRecMoney = order.getQuotedPrice().subtract(recedMoney).add(temp.getRecMoney());
        AssertUtil.isTrue(receipt.getRecMoney().compareTo(reRecMoney) <= 0, "总回款金额不能大于排期执行价");
        receipt.setStatus(Constants.RECEIPT_STATUS_FILLIN);
        receipt.setIsDelete(false);
        this.update(receipt);
        operationService.saveOperation(Constants.OPER_TABLE_RECEIPT, receipt.getId(), Constants.OPER_EDIT, loginUser, null);
        //发送待办消息
        BacklogSocket.sendBacklogMessage(Constants.MENU_BACKLOG_RECEIPT_AUDIT);
    }

    @Override
    public int deleteInfoByIds(String ids) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        String[] idArr = ids.split(",");
        int i = 0;
        for (String id : idArr) {
            ReceiptDO receipt = this.getById(Long.valueOf(id));
            AssertUtil.notNull(receipt, "信息不存在");
            AssertUtil.isTrue(receipt.getStatus() == Constants.RECEIPT_STATUS_FILLIN || receipt.getStatus() == Constants.RECEIPT_STATUS_NOPASS, "该申请已审核通过，无法删除");
            i += this.setDelete(receipt);
            operationService.saveOperation(Constants.OPER_TABLE_RECEIPT, receipt.getId(), Constants.OPER_DELETE, loginUser, null);
        }
        //发送待办消息
        BacklogSocket.sendBacklogMessage(Constants.MENU_BACKLOG_RECEIPT_AUDIT);
        return i;
    }

    @Override
    public int setReceiptAuditPass(MultipartFile[] fileList, String ids) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        String[] idArr = ids.split(",");
        int i = 0;
        for (String id : idArr) {
            ReceiptDO receipt = this.getById(Long.valueOf(id));
            AssertUtil.notNull(receipt, "信息不存在");
            AssertUtil.isTrue(receipt.getStatus() == Constants.RECEIPT_STATUS_FILLIN || receipt.getStatus() == Constants.RECEIPT_STATUS_PASSED, "该申请非待审核状态，无法审核");
            OrderDO order = orderService.getById(receipt.getOrderId());
            AssertUtil.notNull(order, "排期信息不存在，非法操作");
            receipt.setStatus(Constants.RECEIPT_STATUS_PASSED);
            receipt.setAuditUserId(loginUser.getId());
            receipt.setAuditDate(new Date());
            i += this.update(receipt);
            //更改排期付款状态
            BigDecimal recedMoney = this.sumByCondition("recMoney", new HashMap<String, Object>(){{
                put("orderId", receipt.getOrderId());
                put("status", Constants.RECEIPT_STATUS_PASSED);
                put("isDelete", false);
            }});
            if (recedMoney.compareTo(order.getQuotedPrice()) >= 0) {
                order.setIsReceipt(true);
                orderService.update(order);
            }
            //删除原有的附件
            receiptVoucherService.deleteByProperty("receiptId", receipt.getId());
            //上传新的附件
            for (MultipartFile file : fileList) {
                OssFileDO ossFile = ossFileService.saveInfo(file);
                ReceiptVoucherDO voucher = new ReceiptVoucherDO();
                voucher.setReceiptId(receipt.getId());
                voucher.setOssFileId(ossFile.getId());
                receiptVoucherService.insert(voucher);
            }
            //记录操作日志
            operationService.saveOperation(Constants.OPER_TABLE_RECEIPT, receipt.getId(), Constants.OPER_PASSED, loginUser, null);
        }
        //发送待办消息
        BacklogSocket.sendBacklogMessage(Constants.MENU_BACKLOG_RECEIPT_AUDIT);
        return i;
    }

    @Override
    public int setReceiptAuditNoPass(String ids, String auditDesc) {
        UserVO loginUser = (UserVO) session.getAttribute(Constants.SESSION_USER);
        AssertUtil.notNull(loginUser, BizExceptionEnum.AUTHFAILURE);
        String[] idArr = ids.split(",");
        int i = 0;
        for (String id : idArr) {
            ReceiptDO receipt = this.getById(Long.valueOf(id));
            AssertUtil.notNull(receipt, "信息不存在");
            AssertUtil.isTrue(receipt.getStatus() == Constants.RECEIPT_STATUS_FILLIN || receipt.getStatus() == Constants.RECEIPT_STATUS_PASSED, "该申请非待审核状态，无法审核");
            receipt.setStatus(Constants.RECEIPT_STATUS_NOPASS);
            receipt.setAuditUserId(loginUser.getId());
            receipt.setAuditDate(new Date());
            receipt.setAuditDesc(auditDesc);
            i += this.update(receipt);
            //记录操作日志
            operationService.saveOperation(Constants.OPER_TABLE_RECEIPT, receipt.getId(), Constants.OPER_NOPASS, loginUser, null);
        }
        //发送待办消息
        BacklogSocket.sendBacklogMessage(Constants.MENU_BACKLOG_RECEIPT_AUDIT);
        return i;
    }

    @Override
    public Map statReceiptInfo(String roleType, Long userId) {
        return receiptDAO.statReceiptInfo(roleType, userId);
    }
}
